﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using EsaProjectRest.Service;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;

namespace EsaProjectRest.Service.Google
{    
    public class MyGoogleClass
    {        
        public List<CustomObject> items { get; set; }                   
    }
    
    public class CustomObject
    {
        public string title { get; set; }
        public string published { get; set; }        
        public CustomObject2 oggetto { get; set; }        
    }
    public class CustomObject2
    {        
        public CustomOggetto replies { get; set; }
        public CustomOggetto plusoners { get; set; }
        public CustomOggetto resharers { get; set; }
    }

    public class CustomOggetto
    {
        public string totalItems { get; set; }        
    }
    
    public class PostGO
    {

        public Boolean UpdateMyPostGo(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();

                string id_google = GetIdGo(id);

                WebRequest request = WebRequest.Create("https://www.googleapis.com/plus/v1/people/" + id_google + "/activities/public?alt=json&maxResults=100&pp=1&key=AIzaSyDsBKGcaYGOF5OMAI1nzm3GPu4c_92VQkI&fb_source=message");

                WebResponse response = request.GetResponse();

                Stream r_stream = response.GetResponseStream();

                //convert it
                StreamReader response_stream = new StreamReader(r_stream, System.Text.Encoding.GetEncoding("utf-8"));

                string jSon = response_stream.ReadToEnd();

                //clean up your stream
                response_stream.Close();

                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                string json_modify = jSon.Replace("object", "oggetto");

                MyGoogleClass result = jsSerializer.Deserialize<MyGoogleClass>(json_modify);

                string message;
                string message_date;
                string comments;
                string likes;
                string condivisioni;
                int month_attuale = (int)System.DateTime.Now.Month - 1;
                int day_attuale = (int)System.DateTime.Now.Day;
                char[] split = { 'T' };
                char[] split2 = { '-' };
                
                foreach (var item in result.items)
                {
                    message = item.title;
                    comments = item.oggetto.replies.totalItems;
                    likes = item.oggetto.plusoners.totalItems;
                    condivisioni = item.oggetto.resharers.totalItems;
                    message_date = item.published;
                    string[] data = message_date.Split(split);
                    string[] date_go = data[0].Split(split2);
                    int day = int.Parse(date_go[2]);
                    int month = int.Parse(date_go[1]);
                    //System.Diagnostics.Debug.Print("Date: " + day.ToString()+" / "+month.ToString());
                    if ((day <= day_attuale && month == month_attuale + 1) || (day >= day_attuale && month == month_attuale))
                    {
                        //System.Diagnostics.Debug.Print("Date: " + day.ToString()+" / "+month.ToString());
                        DataSet vds = new DataSet();
                        string vsql = string.Format("SELECT Id FROM [Post] WHERE (Id_user = '" + id + "') and (Message = '" + HttpUtility.HtmlEncode(message) + "') and (Date = '" + message_date + "') and (SocialNetwork = 'Google')");
                        SqlCommand vCom = new SqlCommand(vsql, service1.conn);
                        SqlDataAdapter vda = new SqlDataAdapter(vCom);
                        vda.Fill(vds);

                        try
                        {
                            //memorize id
                            string id_post = vds.Tables[0].Rows[0]["Id"].ToString();
                            //System.Diagnostics.Debug.Print("Id_post: " + id_post);
                            vda.Dispose();
                            string sql2 = string.Format("UPDATE [Post] SET N_Likes='" + likes + "',N_Comments='" + comments + "',N_Shares='" + condivisioni + "' WHERE (Id = '" + id_post + "') ");
                            SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                            com2.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);                
            }
            return true;
        }

        public Boolean MyPostGoPrime(string id)
        {
            ServiceRest service1 = new ServiceRest();
            try
            {
                service1.OpenConnection();
                string id_google = GetIdGo(id);

                WebRequest request = WebRequest.Create("https://www.googleapis.com/plus/v1/people/" + id_google + "/activities/public?alt=json&maxResults=100&pp=1&key=AIzaSyDsBKGcaYGOF5OMAI1nzm3GPu4c_92VQkI&fb_source=message");

                WebResponse response = request.GetResponse();

                Stream r_stream = response.GetResponseStream();

                //convert it
                StreamReader response_stream = new StreamReader(r_stream, System.Text.Encoding.GetEncoding("utf-8"));

                string jSon = response_stream.ReadToEnd();

                //clean up your stream
                response_stream.Close();                

                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                string json_modify = jSon.Replace("object", "oggetto");                
                
                MyGoogleClass result = jsSerializer.Deserialize<MyGoogleClass>(json_modify);
                
                //List<page> p = Newtonsoft.Json.JsonConvert.DeserializeObject<List<page>>(jSon);

                string[] message = new string[50];
                string[] message_date = new string[50];
                string[] comments = new string[50];
                string[] likes = new string[50];
                string[] condivisioni = new string[50];
                int i = 0;
                int count = 0;
                                
                foreach (var item in result.items)
                {
                    message[i] = item.title;
                    comments[i] = item.oggetto.replies.totalItems;
                    likes[i] = item.oggetto.plusoners.totalItems;
                    condivisioni[i] = item.oggetto.resharers.totalItems;
                    message_date[i] = item.published;
                    i++;
                    count++;                                                                              
                }
                 
                for (int j = count - 1; j >= 0; j--)
                {
                    if (message[j] != null && message[j] != "")
                    {
                        string sql2 = string.Format("INSERT INTO [Post](Id_user,Message,Date,SocialNetwork,N_Likes,N_Comments,N_Shares) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", id, HttpUtility.HtmlEncode(message[j]), message_date[j], "Google", int.Parse(likes[j]), int.Parse(comments[j]), int.Parse(condivisioni[j]));
                        System.Diagnostics.Debug.Print("sql: " +sql2);
                        SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                        com2.ExecuteNonQuery();
                    }
                }
                //service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore GO prime");
                service1.CloseConnection();
                return false;
            }
        }

        public Boolean MyPostsGO(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();
            
            try
            {
                service1.OpenConnection();
                try
                {                    
                    DataSet vds = new DataSet();
                    string sql = string.Format("SELECT Id_user,Message,Date FROM [Post] WHERE (Id_user = '" + id + "') and (SocialNetwork = 'Google') ORDER BY Date DESC");
                    SqlCommand vCom = new SqlCommand(sql, service1.conn);
                    SqlDataAdapter vda = new SqlDataAdapter(vCom);
                    vda.Fill(vds);
                    string message_user = vds.Tables[0].Rows[0]["Message"].ToString();
                    string date_user = vds.Tables[0].Rows[0]["Date"].ToString();
                    //System.Diagnostics.Debug.Print(message_user);

                    vda.Dispose();
                    string id_google = GetIdGo(id);

                    WebRequest request = WebRequest.Create("https://www.googleapis.com/plus/v1/people/" + id_google + "/activities/public?alt=json&maxResults=100&pp=1&key=AIzaSyDsBKGcaYGOF5OMAI1nzm3GPu4c_92VQkI&fb_source=message");

                    WebResponse response = request.GetResponse();

                    Stream r_stream = response.GetResponseStream();

                    //convert it
                    StreamReader response_stream = new StreamReader(r_stream, System.Text.Encoding.GetEncoding("utf-8"));

                    string jSon = response_stream.ReadToEnd();

                    //clean up your stream
                    response_stream.Close();                    

                    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                    string json_modify = jSon.Replace("object", "oggetto");

                    MyGoogleClass result = jsSerializer.Deserialize<MyGoogleClass>(json_modify);                 

                    string[] message = new string[50];
                    string[] message_date = new string[50];
                    string[] comments = new string[50];
                    string[] likes = new string[50];
                    string[] condivisioni = new string[50];
                    int i = 0;
                    int count = 0;
                    
                    foreach (var item in result.items)
                    {
                        message[i] = item.title;
                        message_date[i] = item.published;
                        comments[i] = item.oggetto.replies.totalItems;
                        likes[i] = item.oggetto.replies.totalItems;
                        condivisioni[i] = item.oggetto.resharers.totalItems;
                        i++;
                        count++;
                        //System.Diagnostics.Debug.Print("adassdad: " + item.fullImage.ToString());
                    }
                    
                    for (int j = 0; j < count; j++)
                    {
                        if ((HttpUtility.HtmlEncode(message[j]) != message_user) && (message_date[j] != date_user))
                        {                            
                            if (message[j].ToString() != "")
                            {
                                string sql2 = string.Format("INSERT INTO [Post](Id_user,Message,Date,SocialNetwork,N_Likes,N_Comments,N_Shares) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", id, HttpUtility.HtmlEncode(message[j]), message_date[j], "Google", int.Parse(likes[j]), int.Parse(comments[j]), int.Parse(condivisioni[j]));
                                SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                                com2.ExecuteNonQuery();
                            }
                        }
                        else
                        {
                            j = count + 1;
                        }
                    }

                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    System.Diagnostics.Debug.Print("Chiamo GO Prime");
                    Boolean ris = MyPostGoPrime(id);
                }
                service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore GO");
                service1.CloseConnection();
                return false;
            }

        }
       

        private string GetIdGo(string id_google)
        {
            Services services = new Services();

            string service ="Google";

            string access_token = services.ReadToken(id_google,service);

            char[] delimiter = { ';' };

            string[] id_go_split = access_token.Split(delimiter);

            return id_go_split[1];
            

        }

           
    }
}
